import { Card, Form, Input, Select, Button, message, Modal, Row, Col, Divider, Space, Descriptions } from '@/utils/antd-imports';
import { ArrowLeftOutlined, ArrowRightOutlined, SaveOutlined, RollbackOutlined, EyeOutlined, FileTextOutlined, TeamOutlined, SafetyCertificateOutlined } from '@/utils/icons';
import React, { useState, useEffect, useRef } from 'react';
import { companyApi } from '@/api/companyApi';
import { customerApi } from '@/api/customerApi';
import employeeApi from '@/api/employeeApi';
import { projectApi } from '@/api/projectApi';
import { contractApi } from '@/api/contractApi';
import { contractPersonnelApi } from '@/api/contractPersonnelApi';
import { projectAcceptanceApi, acceptanceMemberApi } from '@/api/projectAcceptanceApi';
import { warningApi } from '@/api/warningApi';
import fileApi from '@/api/fileApi';
import formDebugger from '@/utils/formDebugger';
import websocketStatus from '@/utils/websocketStatus';

import Steps from 'antd/es/steps';


import DatePicker from 'antd/es/date-picker';
import InputNumber from 'antd/es/input-number';










import dayjs from 'dayjs';
import ContractStep from './ContractStep';
import AcceptanceStep from './AcceptanceStep';

const { Step } = Steps;
const { Option } = Select;
const { TextArea } = Input;

// 项目类型选项
const projectTypes = [
  { value: '1', label: '人力项目' },
  { value: '2', label: '整包项目' },
  { value: '3', label: '分包项目' }
];

const ProjectEditForm = ({ mode = 'create', projectId, projectCode, projectName, subProjectName, onBack }) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();
  const [contractForm] = Form.useForm();
  const [acceptanceForm] = Form.useForm();
  const [projectData, setProjectData] = useState({});
  const [customerSearch, setCustomerSearch] = useState('');
  const [companySearch, setCompanySearch] = useState('');
  const [managerSearch, setManagerSearch] = useState('');
  const [directorSearch, setDirectorSearch] = useState('');
  const [previewVisible, setPreviewVisible] = useState(false);
  
  // API数据状态
  const [customers, setCustomers] = useState([]);
  const [companies, setCompanies] = useState([]);
  const [managers, setManagers] = useState([]);
  const [directors, setDirectors] = useState([]);
  const [loadingCustomers, setLoadingCustomers] = useState(false);
  const [loadingCompanies, setLoadingCompanies] = useState(false);
  const [loadingManagers, setLoadingManagers] = useState(false);
  const [loadingDirectors, setLoadingDirectors] = useState(false);

  // 使用 ref 存储初始值
  const initialValues = useRef({});
  
  // 追踪哪些部分被修改了
  const [modifiedSteps, setModifiedSteps] = useState({
    step0: false,  // 项目基本信息是否被修改
    step1: false,  // 合同信息是否被修改
    step2: false   // 验收配置是否被修改
  });

  // 同步表单值到项目数据
  useEffect(() => {
    if (projectData.step0) {
      form.setFieldsValue(projectData.step0);
    }
  }, [projectData.step0, form]);

  // 确保表单数据同步到项目数据
  useEffect(() => {
    const currentFormValues = form.getFieldsValue();
    if (currentFormValues && Object.keys(currentFormValues).length > 0) {
      setProjectData(prev => ({
        ...prev,
        step0: {
          ...prev.step0,
          ...currentFormValues
        }
      }));
    }
  }, [form]);

  // 监听表单值变化，同步到项目数据
  const handleFormValuesChange = (changedValues, allValues) => {
    setProjectData(prev => ({
      ...prev,
      step0: {
        ...prev.step0,
        ...allValues
      }
    }));
    
    // 编辑模式下，检测项目基本信息是否被修改
    if (mode === 'edit' && Object.keys(changedValues).length > 0) {
      setModifiedSteps(prev => ({
        ...prev,
        step0: true
      }));
    }
  };

  // 监听合同表单值变化
  const handleContractFormValuesChange = (changedValues, allValues) => {
    setProjectData(prev => ({
      ...prev,
      step1: {
        ...prev.step1,
        ...allValues
      }
    }));
    
    // 编辑模式下，检测合同信息是否被修改
    if (mode === 'edit' && Object.keys(changedValues).length > 0) {
      setModifiedSteps(prev => ({
        ...prev,
        step1: true
      }));
    }
  };

  // 监听验收表单值变化
  const handleAcceptanceFormValuesChange = (changedValues, allValues) => {
    setProjectData(prev => ({
      ...prev,
      step2: {
        ...prev.step2,
        ...allValues
      }
    }));
    
    // 编辑模式下，检测验收配置是否被修改
    if (mode === 'edit' && Object.keys(changedValues).length > 0) {
      setModifiedSteps(prev => ({
        ...prev,
        step2: true
      }));
    }
  };

  // 加载客户数据
  const loadCustomers = async () => {
    try {
      setLoadingCustomers(true);
      const response = await customerApi.getAllCustomers();
      if (response.data) {
        setCustomers(response.data);
      }
    } catch (error) {
      console.error('加载客户数据失败:', error);
      message.error('加载客户数据失败');
    } finally {
      setLoadingCustomers(false);
    }
  };

  // 加载公司数据
  const loadCompanies = async () => {
    try {
      setLoadingCompanies(true);
      const response = await companyApi.getAllCompanies();
      if (response.data) {
        setCompanies(response.data);
      }
    } catch (error) {
      console.error('加载公司数据失败:', error);
      message.error('加载公司数据失败');
    } finally {
      setLoadingCompanies(false);
    }
  };

  // 加载管理人员数据
  const loadManagers = async () => {
    try {
      setLoadingManagers(true);
      const response = await employeeApi.getAllActiveEmployees();
      if (response.data) {
        setManagers(response.data);
      }
    } catch (error) {
      console.error('加载管理人员数据失败:', error);
      message.error('加载管理人员数据失败');
    } finally {
      setLoadingManagers(false);
    }
  };

  // 加载总监数据
  const loadDirectors = async () => {
    try {
      setLoadingDirectors(true);
      const response = await employeeApi.getAllActiveEmployees();
      if (response.data) {
        setDirectors(response.data);
      }
    } catch (error) {
      console.error('加载总监数据失败:', error);
      message.error('加载总监数据失败');
    } finally {
      setLoadingDirectors(false);
    }
  };

  // 步骤配置
  const steps = [
    {
      title: '项目基本信息',
      icon: <FileTextOutlined />,
    },
    {
      title: '合同与人员',
      icon: <TeamOutlined />,
    },
    {
      title: '验收配置',
      icon: <SafetyCertificateOutlined />,
    },
  ];

  // 初始化表单数据
  useEffect(() => {
    const loadProjectData = async () => {
      try {
        // 检查WebSocket连接状态
        websocketStatus.checkConnection();
        
        // 加载基础数据
        await Promise.all([
          loadCustomers(),
          loadCompanies(),
          loadManagers(),
          loadDirectors()
        ]);
        
        // 如果是在编辑模式下且有projectId，则从API获取项目数据
        if ((mode === 'edit' || projectId) && projectId) {
          try {
            const projectResponse = await projectApi.getProjectDetail(projectId);
            if (projectResponse && projectResponse.code === 200 && projectResponse.data) {
              const projectData = projectResponse.data;
              
              // 格式化日期
              const formatDate = (dateStr) => {
                if (!dateStr) return null;
                return dayjs(dateStr);
              };
              
              // 获取合同信息
              const contractsResponse = await projectApi.getContractsByProjectId(projectId);
              let contractInfo = { contractPersonnel: [] };
              if (contractsResponse && contractsResponse.code === 200 && contractsResponse.data && contractsResponse.data.length > 0) {
                const contract = contractsResponse.data[0];
                contractInfo = {
                  contractNumber: contract.contractNumber,
                  contractAmount: contract.contractAmount,
                  contractRemarks: contract.contractRemarks
                };
                
                // 获取合同人员 - 使用项目编号查询（合同人员表通过project_code和contract_no关联）
                if (projectData.projectCode) {
                  const personnelResponse = await projectApi.getContractPersonnelByProjectCode(projectData.projectCode);
                  if (personnelResponse && personnelResponse.code === 200 && personnelResponse.data) {
                    contractInfo.contractPersonnel = personnelResponse.data.map(person => ({
                      ...person,
                      startDate: formatDate(person.startDate),
                      endDate: formatDate(person.endDate),
                      isExisting: true // 标记为已有数据
                    }));
                  }
                }
              }
              
              // 获取验收单信息
              const acceptancesResponse = await projectApi.getAcceptancesByProjectId(projectId);
              let acceptancePoints = [];
              if (acceptancesResponse && acceptancesResponse.code === 200 && acceptancesResponse.data) {
                acceptancePoints = acceptancesResponse.data.map(acceptance => ({
                  date: formatDate(acceptance.acceptanceDate),
                  budgetAmount: acceptance.budgetAmount,
                  acceptanceAmount: acceptance.acceptanceAmount,
                  isExisting: true // 标记为已有数据
                }));
              }
              
              const loadedProjectData = {
                step0: {
                  projectNumber: projectData.projectCode || '',
                  projectName: projectData.projectName || '',
                  projectSubname: projectData.projectSubname || subProjectName || '',
                  startDate: formatDate(projectData.startDate),
                  endDate: formatDate(projectData.endDate),
                  estimatedCost: projectData.projectBudget || null,
                  expectedCost: projectData.estimatedCost || null,
                  projectType: projectData.projectType || null,
                  customer: projectData.customerId || null,
                  contractCompany: projectData.contractCompanyId || null,
                  manager: projectData.managerId || null,
                  director: projectData.directorId || null,
                  approvalTemplate: projectData.approvalTemplateId || 1,
                  description: projectData.description || ''
                },
                step1: {
                  ...contractInfo
                },
                step2: {
                  acceptancePoints: acceptancePoints,
                  acceptancePersonnel: [],
                  acceptanceCriteria: '项目验收标准说明',
                  warningDays: 7,
                  warningType: 'email',
                  warningReceivers: [1, 2]
                }
              };
              
              setProjectData(loadedProjectData);
              
              // 确保表单值正确设置
              setTimeout(() => {
                form.setFieldsValue(loadedProjectData.step0);
                // 设置合同表单值，包括合同人员
                contractForm.setFieldsValue({
                  ...loadedProjectData.step1,
                  contractPersonnel: loadedProjectData.step1.contractPersonnel || []
                });
                acceptanceForm.setFieldsValue(loadedProjectData.step2);
              }, 100);
              
              // 存储初始值
              initialValues.current = {
                step0: { ...loadedProjectData.step0 },
                step1: { ...loadedProjectData.step1 },
                step2: { ...loadedProjectData.step2 }
              };
              
              return; // 编辑模式数据加载完成
            }
          } catch (error) {
            console.error('加载项目详情失败:', error);
            message.error('加载项目详情失败');
          }
        }
        
        // 新建模式或加载失败时的默认数据
        const defaultProjectNumber = projectCode ? projectCode : '';
        const defaultProjectName = projectName ? projectName : '';
        
        const mockProjectData = {
          step0: {
            projectNumber: defaultProjectNumber,
            projectName: defaultProjectName, // 从props传入或为空
            startDate: null, // 不设置默认值
            endDate: null, // 不设置默认值
            estimatedCost: null, // 不设置默认值
            expectedCost: null,
            projectType: null, // 不设置默认值
            customer: null,
            contractCompany: null,
            manager: null,
            director: null,
            approvalTemplate: 1, // 审批流程模板ID
            description: ''
          },
          step1: {
            contractNumber: `CONTRACT-${projectId || 'NEW'}`,
            contractAmount: 800000,
            contractRemarks: '示例合同备注信息'
          },
          step2: {
            acceptanceCycle: 30,
            acceptancePersonnel: [],
            acceptanceCriteria: '项目验收标准说明',
            warningDays: 7,
            warningType: 'email',
            warningReceivers: [1, 2]
          }
        };
        
        setProjectData(mockProjectData);
        
        // 确保表单值正确设置
        setTimeout(() => {
          form.setFieldsValue(mockProjectData.step0);
          contractForm.setFieldsValue(mockProjectData.step1);
          acceptanceForm.setFieldsValue(mockProjectData.step2);
        }, 100);
        
        // 存储初始值
        initialValues.current = {
          step0: { ...mockProjectData.step0 },
          step1: { ...mockProjectData.step1 },
          step2: { ...mockProjectData.step2 }
        };
      } catch (error) {
        console.error('加载项目数据失败:', error);
        message.error('加载项目数据失败');
      }
    };
    
    loadProjectData();
  }, [mode, projectId, projectCode, projectName, form, contractForm, acceptanceForm]);


  // 处理返回
  const handleBack = () => {
    onBack();
  };

  // 处理上一步
  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    } else {
      handleBack();
    }
  };


  // 处理下一步
  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
    }
  };

  // 处理完成立项
  const handleCompleteProject = async () => {
    try {
      // 首先验证项目基本信息表单
      try {
        await form.validateFields();
      } catch (error) {
        console.log('项目基本信息表单验证失败:', error);
        message.error('请完善项目基本信息');
        setCurrentStep(0); // 跳转到第一步
        return;
      }
      
      // 调试表单数据
      console.log('=== 开始调试表单数据 ===');
      formDebugger.debugMultiStepForm({
        '项目基本信息': form,
        '合同信息': contractForm,
        '验收信息': acceptanceForm
      }, projectData);
      
      // 获取所有步骤的表单数据
      const basicInfo = form.getFieldsValue();
      const contractInfo = contractForm.getFieldsValue();
      const acceptanceInfo = acceptanceForm.getFieldsValue();
      
      // 如果表单数据为空，尝试从项目数据中获取
      const finalBasicInfo = Object.keys(basicInfo).length > 0 ? basicInfo : (projectData.step0 || {});
      const finalContractInfo = Object.keys(contractInfo).length > 0 ? contractInfo : (projectData.step1 || {});
      const finalAcceptanceInfo = Object.keys(acceptanceInfo).length > 0 ? acceptanceInfo : (projectData.step2 || {});
      
      // 获取当前的projectId（编辑模式下从props获取，创建模式下在创建后从响应获取）
      const currentProjectId = mode === 'edit' ? projectId : null;
      
      console.log('最终项目基本信息:', finalBasicInfo);
      console.log('最终合同信息:', finalContractInfo);
      console.log('最终验收信息:', finalAcceptanceInfo);
      
      // 验证数据完整性
      const basicValidation = formDebugger.validateFormData(finalBasicInfo, [
        'projectName', 'startDate', 'endDate', 'estimatedCost', 'projectType'
      ]);
      
      if (!basicValidation.isValid) {
        message.error(`项目基本信息缺少必填字段: ${basicValidation.missingFields.join(', ')}`);
        setCurrentStep(0); // 跳转到第一步
        return;
      }
      
      // 验证必填字段
      if (!finalBasicInfo.projectName || finalBasicInfo.projectName.trim() === '') {
        message.error('项目名称不能为空');
        return;
      }
      
      if (!finalBasicInfo.startDate) {
        message.error('请选择开始时间');
        return;
      }
      
      if (!finalBasicInfo.endDate) {
        message.error('请选择结束时间');
        return;
      }
      
      if (!finalBasicInfo.estimatedCost) {
        message.error('请输入项目预算');
        return;
      }
      
      if (!finalBasicInfo.projectType) {
        message.error('请选择项目类型');
        return;
      }
      
      // 显示加载状态
      const hideLoading = message.loading(
        mode === 'edit' ? '正在更新项目，请稍候...' : '正在创建项目，请稍候...', 
        0
      );
      
      try {
        // 编辑模式：增量更新逻辑
        if (mode === 'edit' && currentProjectId) {
          console.log('编辑模式：开始增量更新...');
          
          // 检测哪些部分被修改了
          const hasBasicInfoChanges = JSON.stringify(projectData.step0) !== JSON.stringify(initialValues.current.step0);
          const hasContractChanges = JSON.stringify(projectData.step1) !== JSON.stringify(initialValues.current.step1);
          const hasAcceptanceChanges = JSON.stringify(projectData.step2) !== JSON.stringify(initialValues.current.step2);
          
          console.log('修改检测:', { hasBasicInfoChanges, hasContractChanges, hasAcceptanceChanges });
          
          // 更新项目基本信息（如果有修改）
          if (hasBasicInfoChanges) {
            console.log('步骤1: 更新项目基本信息...');
            const projectUpdateData = {
              projectCode: finalBasicInfo.projectNumber || null,
              projectName: finalBasicInfo.projectName.trim(),
              projectSubname: finalBasicInfo.projectSubname || null,
              startDate: finalBasicInfo.startDate ? finalBasicInfo.startDate.format('YYYY-MM-DD') : null,
              endDate: finalBasicInfo.endDate ? finalBasicInfo.endDate.format('YYYY-MM-DD') : null,
              projectBudget: finalBasicInfo.estimatedCost,
              estimatedCost: finalBasicInfo.expectedCost || null,
              projectType: finalBasicInfo.projectType,
              customerId: finalBasicInfo.customer || null,
              contractCompanyId: finalBasicInfo.contractCompany || null,
              managerId: finalBasicInfo.manager || null,
              directorId: finalBasicInfo.director || null,
              approvalTemplateId: finalBasicInfo.approvalTemplate || null,
              description: finalBasicInfo.description || null
            };
            
            const updateResponse = await projectApi.updateProject(currentProjectId, projectUpdateData);
            if (!updateResponse || updateResponse.code !== 200) {
              throw new Error(updateResponse?.message || '更新项目基本信息失败');
            }
            console.log('项目基本信息更新成功');
          } else {
            console.log('项目基本信息未修改，跳过更新');
          }
          
          // 更新合同信息（如果有修改） - 注意：只更新已存在的合同，不创建新合同
          if (hasContractChanges) {
            console.log('步骤2: 更新合同信息...');
            // 获取现有合同
            const contractsResponse = await projectApi.getContractsByProjectId(currentProjectId);
            if (contractsResponse && contractsResponse.code === 200 && contractsResponse.data && contractsResponse.data.length > 0) {
              const existingContract = contractsResponse.data[0];
              const contractUpdateData = {
                projectId: currentProjectId,
                contractNumber: finalContractInfo.contractNumber || existingContract.contractNumber,
                contractAmount: finalContractInfo.contractAmount || existingContract.contractAmount,
                contractRemarks: finalContractInfo.contractRemarks || existingContract.contractRemarks
              };
              
              // 调用更新合同的API
              const updateContractResponse = await contractApi.updateContract(existingContract.id, contractUpdateData);
              if (updateContractResponse && updateContractResponse.code === 200) {
                console.log('合同信息更新成功');
              } else {
                console.warn('合同信息更新失败:', updateContractResponse?.message);
              }
            } else {
              console.warn('未找到现有合同，跳过合同更新（编辑模式下不允许创建新合同）');
            }
          } else {
            console.log('合同信息未修改，跳过更新');
          }
          
          hideLoading();
          message.success('项目更新成功！');
          
          // 返回到项目列表
          onBack({
            type: 'project-form-complete',
            projectId: currentProjectId,
            projectName: finalBasicInfo.projectName,
            projectCode: finalBasicInfo.projectNumber,
            close: true,
            refresh: true
          });
          
          return; // 编辑模式完成，提前返回
        }
        
        // 创建模式：原有的创建逻辑
        console.log('创建模式：开始创建新项目...');
        // 第一步：创建项目基本信息
        console.log('步骤1: 创建项目基本信息...');
        const projectCreateData = {
          projectCode: finalBasicInfo.projectNumber || null,
          projectName: finalBasicInfo.projectName.trim(),
          projectSubname: finalBasicInfo.projectSubname || null,
          startDate: finalBasicInfo.startDate ? finalBasicInfo.startDate.format('YYYY-MM-DD') : null,
          endDate: finalBasicInfo.endDate ? finalBasicInfo.endDate.format('YYYY-MM-DD') : null,
          projectBudget: finalBasicInfo.estimatedCost,
          estimatedCost: finalBasicInfo.expectedCost || null,
          projectType: finalBasicInfo.projectType,
          customerId: finalBasicInfo.customer || null,
          contractCompanyId: finalBasicInfo.contractCompany || null,
          managerId: finalBasicInfo.manager || null,
          directorId: finalBasicInfo.director || null,
          approvalTemplateId: finalBasicInfo.approvalTemplate || null, // 审批流程模板ID
          description: finalBasicInfo.description || null,
          status: 'in_progress',
          createdBy: 1
        };
        
        console.log('准备发送的数据:', projectCreateData);
        const projectResponse = await projectApi.createProject(projectCreateData);
        if (!projectResponse || projectResponse.code !== 200) {
          throw new Error(projectResponse?.message || '创建项目失败');
        }
        
        const projectId = projectResponse.data;
        console.log('项目创建成功，项目ID:', projectId);
        
        // 第二步：上传合同附件文件
        console.log('步骤2: 上传合同附件文件...');
        let contractAttachmentPaths = [];
        if (finalContractInfo.contractAttachment && finalContractInfo.contractAttachment.length > 0) {
          for (const file of finalContractInfo.contractAttachment) {
            if (file.originFileObj) {
              const uploadResult = await fileApi.uploadProjectContract(
                finalBasicInfo.projectName, 
                file.originFileObj
              );
              if (uploadResult.success) {
                contractAttachmentPaths.push(uploadResult.data.filePath);
              }
            }
          }
        }
        
        // 第三步：创建合同
        console.log('步骤3: 创建合同...');
        // 生成唯一的合同编号
        const uniqueContractNumber = finalContractInfo.contractNumber || `CONTRACT-${projectId}-${Date.now()}`;
        const contractData = {
          projectId: projectId,
          contractNumber: uniqueContractNumber,
          contractAmount: finalContractInfo.contractAmount || 0,
          contractRemarks: finalContractInfo.contractRemarks || '',
          contractAttachment: contractAttachmentPaths.join(',')
        };
        
        const contractResponse = await contractApi.createContract(contractData);
        if (!contractResponse || contractResponse.code !== 200) {
          throw new Error(contractResponse?.message || '创建合同失败');
        }
        
        const contractId = contractResponse.data;
        console.log('合同创建成功，合同ID:', contractId);
        
        // 第四步：创建合同人员配置
        console.log('步骤4: 创建合同人员配置...');
        if (finalContractInfo.contractPersonnel && finalContractInfo.contractPersonnel.length > 0) {
          // 获取所有员工信息以便根据ID查找姓名
          let employees = [];
          try {
            const employeeResponse = await employeeApi.getAllActiveEmployees();
            if (employeeResponse && employeeResponse.data) {
              employees = employeeResponse.data;
            }
          } catch (error) {
            console.warn('获取员工信息失败:', error);
          }
          
          const personnelData = finalContractInfo.contractPersonnel.map(person => {
            // 根据员工ID查找员工姓名
            const employee = employees.find(emp => emp.id === person.employee);
            const employeeName = employee ? employee.name : '未知人员';
            
            return {
              projectCode: projectCreateData.projectCode,
              contractNo: contractId || null,
              personnelName: employeeName,
              personnelType: person.type || '正式员工',
              position: person.position || '',
              department: person.department || '',
              team: person.team || '',
              startDate: person.startDate || null,
              endDate: person.endDate || null,
              unitPrice: person.price || 0,
              priceType: person.priceType || 'hour',
              status: 'active',
              remark: person.remark || ''
            };
          });
          
          const personnelResponse = await contractPersonnelApi.batchCreateContractPersonnel(personnelData);
          if (!personnelResponse || personnelResponse.code !== 200) {
            console.warn('创建合同人员失败:', personnelResponse?.message);
          } else {
            console.log('合同人员创建成功');
          }
        }
        
        // 第五步：创建验收单
        console.log('步骤5: 创建验收单...');
        if (finalAcceptanceInfo.acceptancePoints && finalAcceptanceInfo.acceptancePoints.length > 0) {
          // 获取所有员工信息以便根据ID查找详细信息
          let employees = [];
          try {
            const employeeResponse = await employeeApi.getAllActiveEmployees();
            if (employeeResponse && employeeResponse.data) {
              employees = employeeResponse.data;
            }
          } catch (error) {
            console.warn('获取员工信息失败:', error);
          }
          
          // 获取客户信息
          let customerInfo = null;
          if (finalBasicInfo.customer) {
            try {
              const customerResponse = await customerApi.getCustomerById(finalBasicInfo.customer);
              if (customerResponse && customerResponse.data) {
                customerInfo = customerResponse.data;
              }
            } catch (error) {
              console.warn('获取客户信息失败:', error);
            }
          }
          
          for (let index = 0; index < finalAcceptanceInfo.acceptancePoints.length; index++) {
            const point = finalAcceptanceInfo.acceptancePoints[index];
            
            // 获取验收人员的部门和科室信息
            let acceptancePersonDepartment = null;
            let acceptancePersonSection = null;
            let acceptancePersonName = null;
            
            if (finalAcceptanceInfo.acceptancePersonnel && finalAcceptanceInfo.acceptancePersonnel.length > 0) {
              const acceptancePerson = employees.find(emp => emp.id === finalAcceptanceInfo.acceptancePersonnel[0]);
              if (acceptancePerson) {
                acceptancePersonName = acceptancePerson.name;
                acceptancePersonDepartment = acceptancePerson.department || null;
                acceptancePersonSection = acceptancePerson.section || null;
              }
            }
            
            // 创建验收单
            const acceptanceData = {
              acceptanceNo: `AC${projectId}_${index + 1}_${new Date().getTime()}`,
              projectId: projectId,
              projectName: finalBasicInfo.projectName,
              projectCode: finalBasicInfo.projectNumber,
              subProjectName: finalBasicInfo.projectSubname || null, // 使用项目基本信息中的子项目名称
              contactPerson: finalBasicInfo.contactPerson || null,
              client: customerInfo ? customerInfo.name : null, // 使用项目基本信息中配置的客户名称
              department: acceptancePersonDepartment, // 使用验收人员的部门
              section: acceptancePersonSection, // 使用验收人员的科室
              contractNo: finalContractInfo.contractNumber || null,
              acceptanceDate: point.date ? point.date.format('YYYY-MM-DD') : null,
              priority: point.priority || 3,
              startDate: finalBasicInfo.startDate ? finalBasicInfo.startDate.format('YYYY-MM-DD') : null,
              endDate: finalBasicInfo.endDate ? finalBasicInfo.endDate.format('YYYY-MM-DD') : null,
              workType: 'hour', // 默认工时类型为小时
              acceptancePersonId: finalAcceptanceInfo.acceptancePersonnel?.[0] || null,
              acceptancePersonName: acceptancePersonName,
              acceptanceStandard: finalAcceptanceInfo.acceptanceCriteria || null,
              budgetAmount: point.budgetAmount || 0.00,
              acceptanceAmount: point.acceptanceAmount || 0.00,
              status: '待验收',
              remark: point.remark || null
            };
            
            const acceptanceResponse = await projectAcceptanceApi.createAcceptance(acceptanceData);
            if (!acceptanceResponse || acceptanceResponse.code !== 200) {
              console.warn('创建验收单失败:', acceptanceResponse?.message);
            } else {
              console.log('验收单创建成功:', acceptanceData.acceptanceNo);
              
              // 创建验收成员（从合同人员中获取，而不是从验收人员配置中获取）
              if (finalContractInfo.contractPersonnel && finalContractInfo.contractPersonnel.length > 0) {
                const membersData = finalContractInfo.contractPersonnel.map(person => {
                  // 如果合同人员有选择具体的员工，则使用员工信息
                  if (person.employee) {
                    const employee = employees.find(emp => emp.id === person.employee);
                    if (employee) {
                      return {
                        acceptanceId: acceptanceResponse.data.id,
                        employeeId: employee.id,
                        employeeName: employee.name,
                        employeeCode: employee.employeeCode || null,
                        jobTitle: person.position || employee.position || null,
                        unitPrice: person.price || 0.00,
                        priceType: person.priceType || 'hour',
                        estimatedHours: 0.00,
                        actualHours: 0.00,
                        settlementAmount: 0.00,
                        status: '待验收',
                        remark: null
                      };
                    }
                  }
                  
                  // 如果合同人员还没有配置具体的人员，只配置了岗位，员工ID等信息可以为空
                  return {
                    acceptanceId: acceptanceResponse.data.id,
                    employeeId: null, // 可以为空
                    employeeName: null, // 可以为空
                    employeeCode: null, // 可以为空
                    jobTitle: person.position || null, // 岗位名称
                    unitPrice: person.price || 0.00,
                    priceType: person.priceType || 'hour',
                    estimatedHours: 0.00,
                    actualHours: 0.00,
                    settlementAmount: 0.00,
                    status: '待验收',
                    remark: null
                  };
                });
                
                const membersResponse = await acceptanceMemberApi.batchCreateMembers({
                  members: membersData
                });
                
                if (!membersResponse || membersResponse.code !== 200) {
                  console.warn('创建验收成员失败:', membersResponse?.message);
                } else {
                  console.log('验收成员创建成功，共', membersData.length, '人');
                }
              }
            }
          }
        }
        
        // 第六步：创建预警配置
        console.log('步骤6: 创建预警配置...');
        if (finalAcceptanceInfo.warningSettings) {
          // 这里可以根据预警设置创建预警规则
          // 由于预警API主要是查询和处理，配置可能需要在系统设置中完成
          console.log('预警配置已记录，将在系统设置中生效');
        }
        
        hideLoading();
        message.success('项目立项成功！项目、合同、人员、验收节点已全部创建完成。');
        
        // 传递给父组件，通知关闭当前页签并刷新项目列表
        onBack({
          type: 'project-form-complete',
          projectId: projectId,
          projectName: projectCreateData.projectName,
          projectCode: projectCreateData.projectCode,
          close: true,
          refresh: true
        });
        
      } catch (error) {
        hideLoading();
        console.error('立项过程中发生错误:', error);
        
        // 根据错误类型提供更详细的错误信息
        let errorMessage = '项目立项失败：';
        if (error.message) {
          if (error.message.includes('TransactionInactiveError')) {
            errorMessage += '文件上传失败，请重试';
          } else if (error.message.includes('Column \'name\' cannot be null')) {
            errorMessage += '合同人员配置缺少姓名信息，请检查人员配置';
          } else if (error.message.includes('批量创建失败')) {
            errorMessage += '数据保存失败，请检查表单数据完整性';
          } else {
            errorMessage += error.message;
          }
        } else {
          errorMessage += '未知错误，请重试';
        }
        
        message.error(errorMessage);
        
        // 如果是文件上传错误，提供重试建议
        if (error.message && error.message.includes('TransactionInactiveError')) {
          message.warning('建议：请确保文件大小不超过限制，或尝试重新选择文件');
        }
      }
      
    } catch (error) {
      console.error('立项失败:', error);
      message.error('项目立项失败：' + (error.message || '未知错误'));
    }
  };

  // 预览表单
  const handlePreview = () => {
    // 获取当前表单数据
    const currentFormValues = form.getFieldsValue();
    console.log('预览时获取的表单数据:', currentFormValues);
    
    // 更新项目数据
    if (currentFormValues && Object.keys(currentFormValues).length > 0) {
      setProjectData(prev => ({
        ...prev,
        step0: {
          ...prev.step0,
          ...currentFormValues
        }
      }));
    }
    
    setPreviewVisible(true);
  };

  // 渲染预览弹窗
  const renderPreviewModal = () => {
    // 获取当前表单数据
    const currentFormValues = form.getFieldsValue();
    const previewData = {
      step0: currentFormValues && Object.keys(currentFormValues).length > 0 ? currentFormValues : (projectData.step0 || {}),
      step1: currentStep >= 1 ? projectData.step1 || {} : null,
      step2: currentStep >= 2 ? projectData.step2 || {} : null
    };

    return (
      <Modal
        title="项目信息预览"
        visible={previewVisible}
        width={800}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <Descriptions column={1} bordered>
          <Descriptions.Item label="项目编号">{previewData.step0.projectNumber}</Descriptions.Item>
          <Descriptions.Item label="项目名称">{previewData.step0.projectName}</Descriptions.Item>
          <Descriptions.Item label="开始时间">
            {previewData.step0.startDate ? dayjs(previewData.step0.startDate).format('YYYY-MM-DD') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="结束时间">
            {previewData.step0.endDate ? dayjs(previewData.step0.endDate).format('YYYY-MM-DD') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="项目预算">{previewData.step0.estimatedCost || '-'}</Descriptions.Item>
          <Descriptions.Item label="预计成本">{previewData.step0.expectedCost || '-'}</Descriptions.Item>
          <Descriptions.Item label="项目类型">
            {projectTypes.find(t => t.value === previewData.step0.projectType)?.label || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="客户">
            {customers.find(c => c.id === previewData.step0.customer)?.name || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="签约公司主体">
            {companies.find(c => c.id === previewData.step0.contractCompany)?.name || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="项目经理">
            {managers.find(m => m.id === previewData.step0.manager)?.name || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="项目总监">
            {directors.find(d => d.id === previewData.step0.director)?.name || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="项目描述">{previewData.step0.description || '-'}</Descriptions.Item>

          {previewData.step1 && (
            <>
              <Descriptions.Item label="合同编号">{previewData.step1.contractNumber || '-'}</Descriptions.Item>
              <Descriptions.Item label="合同金额">{previewData.step1.contractAmount || '-'}</Descriptions.Item>
              <Descriptions.Item label="合同备注">{previewData.step1.contractRemarks || '-'}</Descriptions.Item>
            </>
          )}

          {previewData.step2 && (
            <>
              <Descriptions.Item label="验收周期">{previewData.step2.acceptanceCycle || '-'}</Descriptions.Item>
              <Descriptions.Item label="验收标准">{previewData.step2.acceptanceCriteria || '-'}</Descriptions.Item>
              <Descriptions.Item label="预警提前天数">{previewData.step2.warningDays || '-'}</Descriptions.Item>
              <Descriptions.Item label="预警方式">{previewData.step2.warningType || '-'}</Descriptions.Item>
            </>
          )}
        </Descriptions>
      </Modal>
    );
  };

  // 渲染第一步：项目基本信息
  const renderBasicInfoStep = () => {
    // 确保表单有正确的初始值
    const formValues = projectData.step0 || {};
    
    return (
      <Card title="项目基本信息" style={{ marginTop: 16 }}>
        <Form
          form={form}
          layout="vertical"
          initialValues={formValues}
          preserve={true}
          onValuesChange={handleFormValuesChange}
        >
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="projectNumber"
              label="项目编号"
              rules={[{ required: false, message: '请输入项目编号' }]}
            >
              <Input 
                placeholder="留空将自动生成项目编号" 
                disabled={!!projectCode} // 如果传入了projectCode，则禁用编辑
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="projectName"
              label="项目名称"
              rules={[{ required: true, message: '请输入项目名称' }]}
            >
              <Input 
                placeholder="请输入项目名称" 
                disabled={!!projectCode || !!projectName} // 如果传入了projectCode或projectName，则禁用编辑
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="projectSubname"
              label="子项目名称"
            >
              <Input placeholder="请输入子项目名称" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="startDate"
              label="开始时间"
              rules={[{ required: true, message: '请选择开始时间' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="endDate"
              label="结束时间"
              rules={[{ required: true, message: '请选择结束时间' }]}
            >
              <DatePicker style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="estimatedCost"
              label="项目预算（元）"
              rules={[{ required: true, message: '请输入项目预算' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                precision={2}
                placeholder="请输入项目预算"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="expectedCost"
              label="预计成本（元）"
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                precision={2}
                placeholder="请输入预计成本"
              />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="projectType"
          label="项目类型"
          rules={[{ required: true, message: '请选择项目类型' }]}
        >
          <Select placeholder="请选择项目类型">
            {projectTypes.map(type => (
              <Option key={type.value} value={type.value}>
                {type.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="customer"
          label="客户"
        >
          <Select
            showSearch
            placeholder="请选择客户"
            loading={loadingCustomers}
            filterOption={false}
            onSearch={setCustomerSearch}
            notFoundContent={loadingCustomers ? '加载中...' : '暂无数据'}
          >
            {customers
              .filter(customer => 
                customer.name?.includes(customerSearch) || 
                customer.code?.includes(customerSearch)
              )
              .map(customer => (
                <Option key={customer.id} value={customer.id}>
                  {customer.name} ({customer.code})
                </Option>
              ))
            }
          </Select>
        </Form.Item>

        <Form.Item
          name="contractCompany"
          label="签约公司主体"
        >
          <Select
            showSearch
            placeholder="请选择签约公司主体"
            loading={loadingCompanies}
            filterOption={false}
            onSearch={setCompanySearch}
            notFoundContent={loadingCompanies ? '加载中...' : '暂无数据'}
          >
            {companies
              .filter(company => 
                company.name?.includes(companySearch) || 
                company.code?.includes(companySearch)
              )
              .map(company => (
                <Option key={company.id} value={company.id}>
                  {company.name} ({company.code})
                </Option>
              ))
            }
          </Select>
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="manager"
              label="项目经理"
            >
              <Select
                showSearch
                placeholder="请选择项目经理"
                loading={loadingManagers}
                filterOption={false}
                onSearch={setManagerSearch}
                notFoundContent={loadingManagers ? '加载中...' : '暂无数据'}
              >
                {managers
                  .filter(manager => 
                    manager.name?.includes(managerSearch) || 
                    manager.position?.includes(managerSearch)
                  )
                  .map(manager => (
                    <Option key={manager.id} value={manager.id}>
                      {manager.name} - {manager.position}
                    </Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="director"
              label="项目总监"
            >
              <Select
                showSearch
                placeholder="请选择项目总监"
                loading={loadingDirectors}
                filterOption={false}
                onSearch={setDirectorSearch}
                notFoundContent={loadingDirectors ? '加载中...' : '暂无数据'}
              >
                {directors
                  .filter(director => 
                    director.name?.includes(directorSearch) || 
                    director.position?.includes(directorSearch)
                  )
                  .map(director => (
                    <Option key={director.id} value={director.id}>
                      {director.name} - {director.position}
                    </Option>
                  ))
                }
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="approvalTemplate"
          label="审批流程模板"
        >
          <Select placeholder="请选择审批流程模板">
            <Option value={1}>标准项目审批流程 (v1.0)</Option>
            <Option value={2}>紧急项目审批流程 (v1.2)</Option>
          </Select>
        </Form.Item>

        <Form.Item name="description" label="项目描述">
          <TextArea rows={4} placeholder="请输入项目描述" />
        </Form.Item>
      </Form>
    </Card>
    );
  };

  // 根据当前步骤渲染对应内容
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return renderBasicInfoStep();
      case 1:
        return <ContractStep key={`contract-${projectId || 'new'}`} form={contractForm} initialValues={projectData.step1} onValuesChange={handleContractFormValuesChange} />;
      case 2:
        return <AcceptanceStep key={`acceptance-${projectId || 'new'}`} form={acceptanceForm} initialValues={projectData.step2} managers={managers} directors={directors} onValuesChange={handleAcceptanceFormValuesChange} />;
      default:
        return renderBasicInfoStep();
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Steps current={currentStep} style={{ marginBottom: 32 }}>
        {steps.map((step, index) => (
          <Step key={index} title={step.title} icon={step.icon} />
        ))}
      </Steps>

      {renderStepContent()}

      <div style={{ 
        marginTop: 24, 
        textAlign: 'center',
        padding: '16px 0',
        borderTop: '1px solid #f0f0f0'
      }}>
        <Space size="large">
          <Button 
            icon={currentStep === 0 ? <RollbackOutlined /> : <ArrowLeftOutlined />} 
            onClick={handlePrev}
            size="large"
          >
            {currentStep === 0 ? '返回' : '上一步'}
          </Button>
          
          {/* 预览按钮只在最后一步显示 */}
          {currentStep === steps.length - 1 && (
            <Button 
              icon={<EyeOutlined />}
              onClick={handlePreview}
              size="large"
            >
              预览
            </Button>
          )}
          
          <Button 
            type="primary" 
            icon={<ArrowRightOutlined />} 
            onClick={currentStep === steps.length - 1 ? handleCompleteProject : handleNext}
            size="large"
          >
            {currentStep === steps.length - 1 ? (mode === 'edit' ? '完成编辑' : '完成立项') : '下一步'}
          </Button>
        </Space>
      </div>

      {/* 预览弹窗 */}
      {renderPreviewModal()}
    </div>
  );
};

export default ProjectEditForm;